//
//  AppDelegate.m
//  WGFGlobalHouses
//
//  Created by waiguofang on 15/4/16.
//  Copyright (c) 2015年 waiguofang. All rights reserved.
//

#import "AppDelegate.h"
#import "LoginViewController.h"
#import "SingletonData.h"
#import "CustomMoviePlayerViewController.h"
#import "UserModal.h"
#import "MainViewController.h"
#import "StringTool.h"
#import "FTWCache.h"
#import "ImgCache.h"
#import "config.h"
#import "TabBarVC.h"
#import "BaseNvc.h"
#import "IWNavigationController.h"

#import "MyXMPP.h"
#import "PushDM.h"
#import "MessageDM.h"
#import "Tools.h"
#import <AudioToolbox/AudioToolbox.h>
#import "MessageVC.h"
#import "DealerMineVc.h"
#import "MiddleManMyVC.h"



@interface AppDelegate ()<MyXMPPDelegate>
@property (strong, nonatomic) UINavigationController *rootNvc;
@property (strong, nonatomic) TabBarVC *mVc;
@end

@implementation AppDelegate
@synthesize isPlayMov,rootNvc,delegate,mVc;



+(AppDelegate *)sharedAppDelegate
{
    return (AppDelegate *)[[UIApplication sharedApplication]delegate];
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    if ([launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey]!=nil) {
//            NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber;
            [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
        }

    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound) categories:nil]];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        
    }else{
        
        [application registerForRemoteNotificationTypes:
         UIRemoteNotificationTypeAlert
         | UIRemoteNotificationTypeBadge
         | UIRemoteNotificationTypeSound];
        
    }
    
    
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    [self loadVc];
    
    [self.window makeKeyAndVisible];
    
    
    if (launchOptions) {
        [PushDM setPushMsgUserAble:NO];
//        [self messageHandler:[self dic2Mod:launchOptions] appInFront:NO];
    }
    
    
    return YES;
}


-(void)loadVc{
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *islogin = [defaults objectForKey:@"login"] ;
    
    if ([StringTool isBlankString:[defaults objectForKey:@"login"]]) {
        islogin = @"NO";
    }
    
    if ([islogin isEqualToString:@"YES"]) {//
        
        if([UserModal shareUserModel2].userType==UserTypeCustomer){
            
            MainViewController *home = [MainViewController new];
            rootNvc =  [[UINavigationController alloc]initWithRootViewController:home];
            [rootNvc setNavigationBarHidden:NO animated:NO];////
            self.window.rootViewController = rootNvc;
            
        }else{
            
            [self home];
        }
        
    }else{
        
        [self goToLogin];
    }
}



-(void)home
{
    
    mVc = [[TabBarVC alloc]init];
    rootNvc =  [[IWNavigationController alloc]initWithRootViewController:mVc];
    
    [rootNvc setNavigationBarHidden:YES animated:NO];
    self.window.rootViewController = rootNvc;
}



-(void)goToLogin
{
    LoginViewController *loginVC = [[LoginViewController alloc]initWithNibName:@"LoginViewController" bundle:nil];
    rootNvc =  [[UINavigationController alloc]initWithRootViewController:loginVC];
    [rootNvc setNavigationBarHidden:YES animated:NO];////
    self.window.rootViewController = rootNvc;
    
}

-(NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    
    if(isPlayMov){
        return UIInterfaceOrientationMaskPortrait|UIInterfaceOrientationMaskLandscapeLeft|UIInterfaceOrientationMaskLandscapeRight;
    }else{
        return UIInterfaceOrientationMaskPortrait;
    }
}




- (void)applicationWillResignActive:(UIApplication *)application {
    
    
    [[MyXMPP sharedMyXMPP] disconnect];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    
    MyXMPP *xp = [MyXMPP sharedMyXMPP];
    xp.delegate = self;
    
    [xp connect];
    
    //取消本地通知
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
//    if ([launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey]!=nil) {
//        NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber;
//    }
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    
    
    if ([PushDM pushMsgUserAble]) {
        [PushDM setPushMsgUserAble:NO];
        
        
//        [self messageHandler:[self dic2Mod:[PushDM getPushMessageRecent]] appInFront:NO];
    }
    
    
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        [FTWCache resetCache];
        
        [ImgCache resetCache];
        
    });
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}



#pragma mark  push
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token = [NSString stringWithFormat:@"%@", deviceToken];
    
    
    [PushDM updataPushToken:token];
    
}


- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSString *error_str = [NSString stringWithFormat: @"%@", error];
    NSLog(@"Failed to get token, error:%@", error_str);
}



#pragma mark anps messsage received;
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    {
        if (application.applicationState == UIApplicationStateActive) {
//            [self messageHandler:[self dic2Mod:userInfo] appInFront:YES];
            [PushDM setPushMsgUserAble:NO];
        }else{
            [PushDM setPushMessageRecent:userInfo];
            [PushDM setPushMsgUserAble:YES];
        }
    }
}


-(MessageModel*)dic2Mod:(NSDictionary*)userInfo{
    
    if (userInfo==nil||userInfo.count==0) {
        return nil;
    }
    
    
    MessageModel *mod = [MessageModel new];
    int type = [[userInfo objectForKey:@"t"] intValue];
    if (type==0) {
        [mod setMessageType:MessageTypeSYS];
        [mod setMessageTitle:@"系统消息"];
    }else if (type==1){
        [mod setMessageType:MessageTypeACTIVITY];
        [mod setMessageTitle:@"楼盘活动"];
    }else if (type==2){
        [mod setMessageType:MessageTypeORDER];
        [mod setMessageTitle:@"交易通知"];
    }else{
        [mod setMessageType:MessageTypeSYS];
        [mod setMessageTitle:@"系统消息"];
    }
    
    [mod setMessageValue:[userInfo objectForKey:@"v"]];
    [mod setMessageSub:[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]];
    [mod setMessageTime:[Tools getNowTime]];
    
    return mod;
}

#pragma mark xmpp messsage received;
- (void)newMessageReceived:(MessageModel *)messageContent{
    
    [self messageHandler:messageContent appInFront:true];
    
}

#pragma mark  收到消息后处理
-(void)messageHandler:(MessageModel*)mod  appInFront:(Boolean)isFront{
    
    if (mod==nil) {
        return;
    }
    
    
    __weak typeof(self) baseSelf = self;
    __block MessageModel *bufMod = mod;
    if (bufMod) {
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            [MessageDM saveMessage:bufMod];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if ([baseSelf.delegate respondsToSelector:@selector(messageReceived:)]) {
                    [baseSelf.delegate messageReceived:bufMod];
                }
                
                
                //AudioServicesPlaySystemSound(1007);
                AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
                
                
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                NSString *islogin = [defaults objectForKey:@"login"] ;
                
                if ([StringTool isBlankString:[defaults objectForKey:@"login"]]) {
                    islogin = @"NO";
                }
                
                if ([islogin isEqualToString:@"YES"]) {//
                
                    if ( mVc.selectedIndex!=3) {
                        
                        UITabBarItem *tabBarItem = [[[mVc tabBar] items] objectAtIndex:3];
                        [tabBarItem setBadgeValue:[NSString stringWithFormat:@"%ld",(long)[MessageDM getMessageNotReadCount]]];
                    }else{
                    
                        UINavigationController *nvc = (UINavigationController*)mVc.selectedViewController;
                        NSArray *vcs = nvc.viewControllers;
                        for (UIViewController *vc in vcs) {
                            
                            if ([vc isKindOfClass:[DealerMineVc class]]) {
                                DealerMineVc *dvc = (DealerMineVc*)vc;
                                [dvc refreshMsgNotReadCount];
                                
                            }else if ([vc isKindOfClass:[MiddleManMyVC class]]){
                                
                                MiddleManMyVC *mvc = (MiddleManMyVC*)vc;
                                [mvc refreshMsgNotReadCount];
                            }
                            
                        }
                    }
                }
            });
        });
    }
}

@end
